package com.itheima.controller;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

/**
 * 短信验证码
 */
@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {
   @Autowired
   private JedisPool jedisPool;

   //为预约体检发送验证码
   @RequestMapping("/send4Order/{telephone}")
   public Result send4Order(@PathVariable String telephone) {
      //1.生成随机验证码
      Integer code = ValidateCodeUtils.generateValidateCode(4);

      try {
         //2.发送验证码
         SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone, String.valueOf(code));
      } catch (ClientException e) {
         e.printStackTrace();
         //3.发送失败直接返回
         return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
      }

      //4.发送成功,保存验证码到redis,5分钟有效
      jedisPool.getResource().setex(telephone + RedisMessageConstant.SENDTYPE_ORDER, 24*60 * 60, String.valueOf(code));

      //5.返回数据
      return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
   }

   //为用户登录发送验证码
   @RequestMapping("/send4Login/{telephone}")
   public Result send4Login(@PathVariable String telephone) {
      //1.生成6位随机验证
      Integer code = ValidateCodeUtils.generateValidateCode(6);

      try {
         //2.发送验证码
         SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone, String.valueOf(code));
      } catch (ClientException e) {
         e.printStackTrace();
         return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
      }

      //3.保存验证码到redis
      jedisPool.getResource().setex(telephone + RedisMessageConstant.SENDTYPE_LOGIN, 60 * 60 * 24, String.valueOf(code));
      return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
   }
}
